package cn.dankal.flyaudio.information.detail;

import android.view.MotionEvent;
import android.view.View;
import android.view.ViewTreeObserver;
import android.widget.EditText;

import androidx.core.widget.NestedScrollView;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.android.arouter.launcher.ARouter;

import butterknife.BindView;
import butterknife.OnClick;
import cn.dankal.basiclib.DKUserManager;
import cn.dankal.basiclib.DankalApplication;
import cn.dankal.basiclib.base.activity.BaseStateActivity;
import cn.dankal.basiclib.protocol.LoginProtocol;
import cn.dankal.basiclib.util.KeyboardChangeListener;
import cn.dankal.basiclib.util.ScreenUtils;
import cn.dankal.basiclib.util.SoftKeyboardUtil;
import cn.dankal.basiclib.util.StringUtil;
import cn.dankal.basiclib.util.ToastUtils;
import cn.dankal.basiclib.widget.swipetoloadlayout.SwipeToLoadLayout;
import cn.dankal.business.pojo.BaseBeanList;
import cn.dankal.business.pojo.CommentBean;
import cn.dankal.business.pojo.CurrentBean;
import cn.dankal.business.pojo.InfoBean;
import cn.dankal.business.pojo.ReasonBean;
import cn.dankal.flyaudio.R;
import cn.dankal.flyaudio.current.post.detail.CommentAdapter;
import cn.dankal.flyaudio.current.post.detail.CommentReplyAdapter;

import static androidx.recyclerview.widget.RecyclerView.VERTICAL;


/**
 * 咨询详情
 */
public class InformationPostDetailActivity extends BaseStateActivity implements InformationContract.View {

    // 评论列表
    @BindView(R.id.rv_post_comments)
    RecyclerView mRvPostComments;

    // 输入编辑
    @BindView(R.id.et_content)
    EditText mEtContent;

    @BindView(R.id.ll_comment)
    View mInBottomInput;

    @BindView(R.id.swipe_toload_layout)
    SwipeToLoadLayout mSwipeToLoadLayout;

    //@Autowired(name = Social.PostDetailActivity.KEY_POST_ID)
    protected String postId;


    protected InformationContract.Presenter mPresenter;
    protected CommentAdapter mAdapter;

    private KeyboardChangeListener keyboardChangeListener;

    protected String commentName;
    protected String commentUuid;
    protected int commentPosition = -1;
    protected String recevierUuid;
    //是否是评论的刷新
    private boolean isComment;


    @Override
    public int getLayoutId() {
        return R.layout.activity_current_detail;
    }


    @Override
    public void initComponents() {
        mPresenter = new InformationPresenter();
        mPresenter.attachView(this);

        keyboardChangeListener = new KeyboardChangeListener(this);
        keyboardChangeListener.setKeyBoardListener((isShow, keyboardHeight) -> {
            if (!isShow) {
                hideBottomInput();
            }
        });

        mSwipeToLoadLayout.setLoadMoreEnabled(false);
        mSwipeToLoadLayout.setRefreshEnabled(true);

        mSwipeToLoadLayout.setOnRefreshListener(this::onRefresh);
        mSwipeToLoadLayout.setOnLoadMoreListener(this::onLoadMore);
        mRvPostComments.setLayoutManager(new LinearLayoutManager(this));
        mRvPostComments.setNestedScrollingEnabled(false);
        mAdapter = new CommentAdapter(true);
        mAdapter.setListener(new CommentReplyAdapter.OnChoiceByUserToReplyListener() {
            @Override
            public void innerComment(String name, String comment_id, String userId, int position) {
                onInnerCommentClick(name, comment_id, userId, position);
            }

            @Override
            public void praise(String uuid, String type, int position) {
                ToastUtils.showShort("点赞成功");
                // 局部刷新 点赞的UI
                if (mAdapter != null && mAdapter.getDatas() != null && mAdapter.getDatas().size() > position) {
                    // 是否点赞：是>=1 否0
                    if (mAdapter.getDatas().get(position).isPraise > 0) {
                        mAdapter.getDatas().get(position).isPraise = 0;
                        int likeCount;
                        try {
                            likeCount = Integer.valueOf(mAdapter.getDatas().get(position).likeNumber);
                        } catch (Exception e) {
                            likeCount = 1;
                        }
                        mAdapter.getDatas().get(position).likeNumber = String.valueOf(likeCount - 1);
                    } else {
                        mAdapter.getDatas().get(position).isPraise = 1;
                        int likeCount;
                        try {
                            likeCount = Integer.valueOf(mAdapter.getDatas().get(position).likeNumber);
                        } catch (Exception e) {
                            likeCount = 1;
                        }
                        mAdapter.getDatas().get(position).likeNumber = String.valueOf(likeCount + 1);
                    }
                    mAdapter.notifyItemChanged(position, "star");
                }
                mPresenter.praise(uuid, type, position);
            }

            @Override
            public void praiseCancel(String uuid, String type, int position) {
                ToastUtils.showShort("取消成功");
                // 局部刷新 点赞的UI
                if (mAdapter != null && mAdapter.getDatas() != null && mAdapter.getDatas().size() > position) {
                    // 是否点赞：是>=1 否0
                    if (mAdapter.getDatas().get(position).isPraise > 0) {
                        mAdapter.getDatas().get(position).isPraise = 0;
                        int likeCount;
                        try {
                            likeCount = Integer.valueOf(mAdapter.getDatas().get(position).likeNumber);
                        } catch (Exception e) {
                            likeCount = 1;
                        }
                        mAdapter.getDatas().get(position).likeNumber = String.valueOf(likeCount - 1);
                    } else {
                        mAdapter.getDatas().get(position).isPraise = 1;
                        int likeCount;
                        try {
                            likeCount = Integer.valueOf(mAdapter.getDatas().get(position).likeNumber);
                        } catch (Exception e) {
                            likeCount = 1;
                        }
                        mAdapter.getDatas().get(position).likeNumber = String.valueOf(likeCount + 1);
                    }
                    mAdapter.notifyItemChanged(position, "star");
                }
                mPresenter.praiseCancel(uuid, type, position);
            }
        });
        mRvPostComments.setAdapter(mAdapter);
        //noinspection deprecation
//      mRvPostComments.addItemDecoration(new DividerItemDecoration(getResources().getColor(R.color.colorE5), dp2px(this, 2)));
        mRvPostComments.addItemDecoration(new DividerItemDecoration(this, VERTICAL));

        //设置webView里字体大小
     /*   WebSettings settings = mWbvPostContents.getSettings();
        settings.setSupportZoom(true);
        settings.setTextSize(WebSettings.TextSize.LARGEST);
        //        // settings.setDefaultFontSize(50);
        //        settings.setJavaScriptEnabled(true);
        //        // 调整图片大小自适应
        //        mWbvPostContents.setWebViewClient(new WebViewUtil.MyWebViewClient());
        settings.setJavaScriptEnabled(true);//支持js
        WebViewUtil.initWebViewSettings(mWbvPostContents, this);
        mWbvPostContents.setWebViewClient(new WebViewUtil.MyWebViewClient());*/

        mEtContent.setOnFocusChangeListener((v, hasFocus) -> {
            if (!hasFocus) {
                SoftKeyboardUtil.hideSoftInput(v);
            }
        });

//        setGlobalLayoutListener();

    }

    public void initData(String uuid) {
        postId = uuid;
        if (!StringUtil.isValid(postId)) {
            ToastUtils.showShort("没有uuid");
            postDelayedToFinish();
            return;
        }
        mPresenter.setUuid(postId);
        mPresenter.onRefresh();
    }

    protected void onInnerCommentClick(String name, String comment_id, String userId, int commentPosition) {

        InformationPostDetailActivity.this.commentName = name;
        InformationPostDetailActivity.this.commentUuid = comment_id;
        InformationPostDetailActivity.this.recevierUuid = userId;
        InformationPostDetailActivity.this.commentPosition = commentPosition;
        showShortBottomInput();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mPresenter != null) {
            mPresenter.detachView();
        }
//      destoryWebview(mWbvPostContents);
        keyboardChangeListener.destroy();

    }

    /*


        private void setCommentNumber() {
            mTvCommentNumber.setVisibility(View.VISIBLE);
            mTvCommentNumber.setText(String.valueOf(comment_count));
        }

        private void setCollectNumber() {
            mTvCollectNumber.setVisibility(View.VISIBLE);
            mTvCollectNumber.setText(String.valueOf(collect_count));
        }

        private void setPraiseNumber() {
            mTvPraiesNumber.setVisibility(View.VISIBLE);
            mTvPraiesNumber.setText(String.valueOf(praise_count));
        }

        @Override
        public void onPraiseResult(BaseResponseBody bodyCase) {
            if ("yes".equals(StringUtil.safeString(isPraise))) {
                isPraise = "no";
                praise_count -= 1;
                mIvPraies.setImageResource(R.mipmap.ic_praise_grey);
            } else {
                isPraise = "yes";
                praise_count += 1;
                mIvPraies.setImageResource(R.mipmap.ic_praise_grey_pressed);
            }
            setPraiseNumber();
            setResult(RESULT_OK);
        }

        @Override
        public void onCollectResult(BaseResponseBody bodyCase) {
            if ("yes".equals(StringUtil.safeString(isCollect))) {
                isCollect = "no";
                collect_count -= 1;
                mIvCollect.setImageResource(R.mipmap.ic_collection);
            } else {
                isCollect = "yes";
                collect_count += 1;
                mIvCollect.setImageResource(R.mipmap.ic_collect_pressed);
            }
            setCollectNumber();
            setResult(RESULT_OK);
        }

        @Override
        public void onRepluResult(BaseResponseBody baseResponseBody) {

            mIvComment.setImageResource(R.mipmap.ic_comments_pressed);
            ToastUtils.showShort("回复成功");
            mPresenter.onRefresh();
            hideBottomInput();
            mEtContent.setText("");
            comment_count += 1;
            setCommentNumber();
            setResult(RESULT_OK);
        }

        @Override
        public void onForumComments(CommentCase commentCase) {
            mSwipeToLoadLayout.setRefreshing(false);
            mSwipeToLoadLayout.setLoadingMore(false);
            List<CommentBean> commentBeans = commentCase.getComments_list();
            if (commentBeans != null && !commentBeans.isEmpty()) {
                mAdapter.loadMore(commentBeans);
                mSwipeToLoadLayout.setLoadMoreEnabled(commentBeans.size() == Constant.PAGE_SIZE);
                mAdapter.bind(commentCase.getComments_list());
                mIvNoCommentHint.setImageResource(R.mipmap.ic_bottom_line);
            } else {
                mIvNoCommentHint.setImageResource(R.mipmap.ic_bottom_nocomment);
                mSwipeToLoadLayout.setLoadMoreEnabled(false);
            }
        }

        @Override
        public void onDelOwnerArticleResult(BaseResponseBody baseResponseBody) {
            ToastUtils.showShort(baseResponseBody.message);
            setResult(RESULT_OK);
            this.finish();
        }


        */
    //发送
    @OnClick(R.id.tv_send)
    public void onViewClicked(View view) {
        if (!DankalApplication.isLogin()) {
            ARouter.getInstance().build(LoginProtocol.LOGIN).navigation();
            return;
        }
        if (DKUserManager.getUserInfo().getUserUuid().equals(recevierUuid)) {
            ToastUtils.showShort("不能评论自己的留言");
            return;
        }

        int et_content_count = mEtContent.getText().length();
        if (et_content_count > 200) {
            ToastUtils.showShort("评论字符限制长度200");
            return;
        }
        String content = mEtContent.getText().toString();
        if (this.commentUuid != null) {
            mPresenter.inside_comment(commentUuid, content, recevierUuid, postId);
            return;
        }
        mPresenter.comment(content, postId);
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            float rawX = ev.getRawX();
            float rawY = ev.getRawY();
            if (!ScreenUtils.calcViewScreenLocation(mInBottomInput).contains(rawX, rawY)) {
                if (SoftKeyboardUtil.isKeyboardShown(mEtContent)) {
                    SoftKeyboardUtil.hideSoftInput(mEtContent);
                } else {
                    hideBottomInput();
                }
            }
        }
        return super.dispatchTouchEvent(ev);
    }

    private boolean isShow, animaing;

    private void showShortBottomInput() {
       /* if (animaing || isShow) {
            return;
        }
        mInBottomInput.animate().setDuration(250).translationYBy(-mInBottomInput.getHeight()).setListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationStart(Animator animation) {
                super.onAnimationStart(animation);
                animaing = true;
            }

            @Override
            public void onAnimationEnd(Animator animation) {
                super.onAnimationEnd(animation);
                animaing = false;
                isShow = true;
            }
        }).start();*/

        SoftKeyboardUtil.showSoftInput(mInBottomInput);


    }


    private void hideBottomInput() {
        /*if (animaing || !isShow) {
            return;
        }
        mInBottomInput.animate().setDuration(250).translationYBy(mInBottomInput.getHeight()).setListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationStart(Animator animation) {
                super.onAnimationStart(animation);
                animaing = true;
            }

            @Override
            public void onAnimationEnd(Animator animation) {
                super.onAnimationEnd(animation);
                animaing = false;
                isShow = false;
            }
        }).start();*/
        SoftKeyboardUtil.hideSoftInput(mInBottomInput);

    }

    @Override
    public void onCommentList(BaseBeanList<CommentBean> commentBeanBaseBeanList) {
        mSwipeToLoadLayout.setRefreshing(false);
        mSwipeToLoadLayout.setLoadingMore(false);
        mAdapter.addMore(commentBeanBaseBeanList.list);
        if (isComment) {
            isComment = false;
            ((NestedScrollView) findViewById(R.id.swipe_target)).smoothScrollTo(0, (int) ScreenUtils.calcViewScreenLocation(findViewById(R.id.iv_tag)).top);
        }
    }

    @Override
    public void onPraiseResult(ReasonBean bodyCase, int position) {

    }

    @Override
    public void onInnerCommentResult(ReasonBean commentCase) {
        mSwipeToLoadLayout.setRefreshing(false);
        mSwipeToLoadLayout.setLoadingMore(false);
        ToastUtils.showShort(commentCase.reason);
    }

    @Override
    public void onCommentResult(ReasonBean reasonBean, CommentBean commentBean) {
        commentName = null;
        commentUuid = null;
        recevierUuid = null;
//      hideBottomInput();
        isComment = true;
        // 如果有位置就在评论的位置插入一条数据
        if (commentPosition != -1 && mAdapter != null && mAdapter.getDatas().size() >= commentPosition) {
            /* 局部刷新数据 */
            CommentBean baseComment = mAdapter.getDatas().get(commentPosition);
            CommentBean.SecondCommentsBean newInsertComment = new CommentBean.SecondCommentsBean();
            newInsertComment.commentUuid = commentBean.uuid;
            newInsertComment.content = commentBean.content;
            newInsertComment.sendName = commentBean.name;
            newInsertComment.receiveName = baseComment.name;
            mAdapter.getDatas().get(commentPosition).list.add(newInsertComment);
            mAdapter.notifyItemChanged(commentPosition);
            mRvPostComments.scrollToPosition(commentPosition);
            commentPosition = -1;
            onRefresh();
        } else {
            onRefresh();
        }

    }

    ViewTreeObserver.OnGlobalLayoutListener onGlobalLayoutListener;

    private void setGlobalLayoutListener() {
        if (onGlobalLayoutListener != null)
            mEtContent.getRootView().getViewTreeObserver().removeGlobalOnLayoutListener(onGlobalLayoutListener);
        //键盘监听
        onGlobalLayoutListener = () -> {
            if (SoftKeyboardUtil.isKeyboardShown(mEtContent.getRootView())) {

                ((NestedScrollView) findViewById(R.id.swipe_target)).smoothScrollTo(0
                        , (int) ScreenUtils.calcViewScreenLocation(findViewById(R.id.iv_tag)).top);
            }
        };
        mEtContent.getRootView().getViewTreeObserver().addOnGlobalLayoutListener(onGlobalLayoutListener);
    }

    @Override
    public void onInfoDetailResult(InfoBean infoBean) {

    }

    @Override
    public void onCurrentDetailResult(CurrentBean currentBean) {

    }

    private void onLoadMore() {
        mPresenter.onLoadMore();
    }

    private void onRefresh() {
        mAdapter.clearData();
        mPresenter.onRefresh();
    }

    @Override
    public Object contentView() {
        return findViewById(R.id.ll_detail);
    }
}
